﻿using System;
using System.Collections.Generic;
using System.Linq;
using ZX.BLL.Extend;
using ZX.DBModule;
using System.Data;
using DevExpress.XtraReports.UI;
using System.Drawing;
using ZX.DAL.DBExtend;

namespace ZX.Web.UI.Controls
{
    public partial class AutoReportView : BasePage
    {
        private int length = 0;
        private string[] _field = null;
        private float[] _colWidth = null;
        private string _strEntity = string.Empty;
        private string _strTable = string.Empty;
        private Guid _functionID = Guid.Empty; //所属
        private string _reportName = string.Empty;
        private string _condition = string.Empty;
        private string _customCondition = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            _strEntity = GetStringFromQueryString("entity", "");
            _functionID = GetGuidFromQueryString("functionID");
            _condition = GetStringFromQueryString("condition", "");
            _customCondition = GetStringFromQueryString("customCondition", "");
            SysReport report = new SysReport();
            CreateBussniess(_strEntity);
            if (_bll == null)
            {
                _bll = new BaseBussnies();
            }
            _bll.entity = report;
            _condition = (_condition == "") ? _bll.GetRoleCondition(this.User, _strEntity, _functionID) : "(" + _bll.GetRoleCondition(this.User, _strEntity, _functionID) + ") and (" + _condition + ")";
            _condition = (_condition == "") ? _customCondition : _condition + " and (" + _customCondition + ")";
            _condition = _condition.Replace("()", "(1=1)");
            ///获取报表文件
            //report = _bll.GetEntityByCondition<SysReport>("EntityName='" + _strEntity + "'");
            //if (report == null)
            //{
            //    Response.Write("没有报表");
            //    return;
            //}

            IList<DataListTemplate> _list = null;
            IList<DataListTemplate> list = null;//;= _bll.GetEntitys<DataListTemplate>("EntityName='"+_strEntity+"'");
            DataListTemplate template = DataListTemplate.CreateInstance();
            BaseBussnies bll = new BaseBussnies(template);
            //自定义列
            UserListTemplate _entity = bll.GetEntityByCondition<UserListTemplate>("EntityName='" + EntityName + "' and AddUser='" + UserId + "'");
            //IList<DataListTemplate> list = null;
            if (_entity != null)
            {
                list = (List<DataListTemplate>)ZX.Common.Globals.JSonToObject<List<DataListTemplate>>(_entity.DataJSON);
            }
            else
            {
                list = bll.GetEntitys<DataListTemplate>("EntityName='" + EntityName + "'");
            }
            if (list != null)
            {
                _list = list.Where(p => p.IsVisiable != "N" && p.iOrder != 0).OrderBy(p => p.iOrder).ToList();
            }



            //

            //rpt.PaperKind = System.Drawing.Printing.PaperKind
            //rpt = DevExpress.XtraReports.UI.XtraReport.FromFile(Server.MapPath("\\upload\\"+report.ReportFile), true);

            string _ReportTemplate = System.IO.File.ReadAllText(Server.MapPath("Report1.repx"));
            _ReportTemplate = _ReportTemplate.Replace("{0}", BuildReportCellCtrl(_list, "0"));
            _ReportTemplate = _ReportTemplate.Replace("{1}", BuildReportCellCtrl(_list, "1"));

            _ReportTemplate = _ReportTemplate.Replace("{2}", BuildReportCell(_list, "0"));
            _ReportTemplate = _ReportTemplate.Replace("{3}", BuildReportCell(_list, "1"));

            _ReportTemplate = _ReportTemplate.Replace("{4}", BuildReportCellArray(_list, "0"));
            _ReportTemplate = _ReportTemplate.Replace("{5}", BuildReportCellArray(_list, "1"));

            _ReportTemplate = _ReportTemplate.Replace("{6}", BuildReportCellInfo(_list, "0"));
            _ReportTemplate = _ReportTemplate.Replace("{7}", BuildReportCellInfo(_list, "1"));
            //.Replace("{2}",BuildReportCellInfo(_list,"0")).Replace("{3}",BuildReportCellCtrl(_list,"1")).Replace("{4}",(_list,"1")).Replace("{5}",(_list,"1"));
            //读取流程
            //this.Response.Write(_ReportTemplate.ToString());
            Byte[] bytes = System.Text.Encoding.UTF8.GetBytes(_ReportTemplate);

            DevExpress.XtraReports.UI.XtraReport rpt = DevExpress.XtraReports.UI.XtraReport.FromStream(new System.IO.MemoryStream(bytes), true);
            rpt.PaperKind = System.Drawing.Printing.PaperKind.A4;
            ////获取字段名
            InitDetailCol(rpt);

            //获取表名
            BaseEntity entity = ZX.Common.Globals.getEntity(_strEntity) as BaseEntity;
            _strTable = (entity == null ? _strEntity : entity.GetTableName());

            CreateReport(rpt);
            ReportViewer1.Report = rpt;
        }


        /// <summary>
        /// 声明
        /// </summary>
        /// <returns></returns>
        private string BuildReportCellCtrl(IList<ZX.DBModule.DataListTemplate> dataTemplateList, string flag)
        {
            System.Text.StringBuilder _CtrlTemplate = new System.Text.StringBuilder("");
            int i = 0;
            foreach (var entity in dataTemplateList)
            {
                //if (i>0)
                //{
                //    //_CtrlTemplate.Append(",");
                //}
                string _Ctrl = string.Format("private DevExpress.XtraReports.UI.XRTableCell {0}" + flag + ";", entity.Field);
                _CtrlTemplate.AppendLine(_Ctrl);
                i = i + 1;
            }
            return _CtrlTemplate.ToString();
        }

        /// <summary>
        /// 声明
        /// </summary>
        /// <returns></returns>
        private string BuildReportCell(IList<ZX.DBModule.DataListTemplate> dataTemplateList, string flag)
        {
            System.Text.StringBuilder _CtrlTemplate = new System.Text.StringBuilder("");
            int i = 0;
            foreach (var entity in dataTemplateList)
            {
                //if (i>0)
                //{
                //    //_CtrlTemplate.Append(",");
                //}
                string _Ctrl = string.Format("this.{0}" + flag + " = new DevExpress.XtraReports.UI.XRTableCell();", entity.Field);
                _CtrlTemplate.AppendLine(_Ctrl);
                i = i + 1;
            }
            return _CtrlTemplate.ToString();
        }


        /// <summary>
        /// 数组
        /// </summary>
        /// <param name="dataTemplateList"></param>
        /// <param name="flag"></param>
        /// <returns></returns>
        private string BuildReportCellArray(IList<ZX.DBModule.DataListTemplate> dataTemplateList, string flag)
        {
            System.Text.StringBuilder _CtrlTemplate = new System.Text.StringBuilder("");
            foreach (var entity in dataTemplateList)
            {
                string _Ctrl = string.Format("this.{0}" + flag + ",", entity.Field);
                _CtrlTemplate.Append(_Ctrl);
            }
            return _CtrlTemplate.ToString().Remove(_CtrlTemplate.ToString().Length - 1, 1);
        }


        /// <summary>
        /// 属性
        /// </summary>
        /// <param name="dataTemplateList"></param>
        /// <param name="flag"></param>
        /// <returns></returns>
        private string BuildReportCellInfo(IList<ZX.DBModule.DataListTemplate> dataTemplateList, string flag)
        {
            System.Text.StringBuilder _CtrlTemplate = new System.Text.StringBuilder("");
            string _Ctrl = @"
            this.{0}{1}.Name = ""{0}{1}"";
            this.{0}{1}.Tag = ""{0}"";
            this.{0}{1}.Text = ""{3}"";
            this.{0}{1}.Width = {2};";
            foreach (var entity in dataTemplateList)
            {
                _CtrlTemplate.AppendLine(string.Format(_Ctrl, entity.Field, flag, entity.Width, entity.THCaption));
            }
            return _CtrlTemplate.ToString();

        }

        private void InitReportHeaderTitle(DevExpress.XtraReports.UI.XtraReport rpt, SysReport report)
        {
            DevExpress.XtraReports.UI.XRLabel ctrl = rpt.FindControl("THeaderTitle", true) as DevExpress.XtraReports.UI.XRLabel;
            if (ctrl.Text.Length == 0)
            {
                ctrl.Text = report.ReportName;
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="rpt"></param>
        private void InitDetailCol(DevExpress.XtraReports.UI.XtraReport rpt)
        {
            DevExpress.XtraReports.UI.XRTable ctrl = rpt.FindControl("TDetail", true) as DevExpress.XtraReports.UI.XRTable;
            length = ctrl.Rows[0].Cells.Count;
            _field = new string[length];
            _colWidth = new float[length];
            for (int i = 0; i < length; i++)
            {
                _field[i] = ctrl.Rows[0].Cells[i].Tag.ToString();
                _colWidth[i] = ctrl.Rows[0].Cells[i].WidthF;
                var cell = ctrl.Rows[0].Cells[0];
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="rpt"></param>
        private void CreateReport(XtraReport rpt)
        {
            FillDataSource(rpt);
            rpt.DataMember = ((DataSet)rpt.DataSource).Tables[0].TableName;
            InitBands(rpt);//添加带区（Bands）
            InitStyles(rpt);//添加Styles
            InitDetailsBasedonXRTable(rpt);//用XRTable显示报表
            //rpt.ShowPreviewDialog();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="rpt"></param>
        public void FillDataSource(XtraReport rpt)
        {
            DbSql dbSql = new DbSql();
            string _order = GetStringFromQueryString("order", "");
            _order = _order == "" ? "" : " order by " + _order;
            System.Data.DataTable dt = new DataTable();
            if (_strTable.ToLower() == "v_wkremtovertimeleave" && !_condition.Contains("AddUser"))
            {
                string sqlorder = " order by LDeptName,CName ";
                string srhSql = @"select EmployeeID,EmployeeCode,CName,LDeptName,
                        SUM(WorkDayOverTime) WorkDayOverTime,SUM(WeekendOverTime) WeekendOverTime,SUM(HolidayOverTime) HolidayOverTime,SUM(TotalOverTime) TotalOverTime,
                        SUM(TiaoxiuTime) TiaoxiuTime,SUM(RemTime) RemTime,dbo.Fn_GetEmployeeRemOvertimeLeave(EmployeeID) RemTiaoxiuTime
                        from V_wkOvertimeLeave
                        where 1=1 {0}
                        group by EmployeeID,EmployeeCode,CName,LDeptName
                        {1}";
                dt = dbSql.ExecuteQuery(string.Format(srhSql, _condition, sqlorder));
            }
            //else if (_strTable.ToLower() == "crmorderpaydelivercollect") //交付明细汇总
            //{
            //    ZX.CRM.Bussiness.BCrmOrderPayDeliverCollect services = new ZX.CRM.Bussiness.BCrmOrderPayDeliverCollect();
            //    ZX.CRM.Library.CrmOrderPayDeliverCollect info = new ZX.CRM.Library.CrmOrderPayDeliverCollect();
            //    string data = this.GetStringFromQueryString("customCondition", "");

            //    DateTime cdt = System.DateTime.Now;
            //    info.BeginDate = cdt.AddDays(1 - cdt.Day);
            //    info.EndDate = info.BeginDate.AddMonths(1).AddDays(-1);

            //    if (!string.IsNullOrEmpty(data))
            //    {
            //        var objEntity = new { BeginDate = string.Empty, EndDate = string.Empty, DeptId = string.Empty, CustomerName = string.Empty, PackName = string.Empty, Product = string.Empty, SaleTypeName = string.Empty };
            //        var obj = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(data, objEntity);
            //        if (obj != null)
            //        {
            //            if (!string.IsNullOrEmpty(obj.BeginDate)) info.BeginDate = Convert.ToDateTime(obj.BeginDate);
            //            if (!string.IsNullOrEmpty(obj.EndDate)) info.EndDate = Convert.ToDateTime(obj.EndDate);
            //            info.DeptId = new Guid(string.IsNullOrEmpty(obj.DeptId) ? "00000000-0000-0000-0000-000000000000" : obj.DeptId);
            //            info.CustomerName = obj.CustomerName;
            //            info.PackName = obj.PackName;
            //            info.Product = obj.Product;
            //            info.SaleTypeName = obj.SaleTypeName;
            //        }
            //    }
            //    int total = 0;
            //    dt = services.Seach(info, 1, 0, 0, out total);
            //}
            else
            {
                dt = dbSql.ExecuteQuery(string.Format("select * from {0} {1} {2}", _strTable, _condition == "" ? "" : " where " + _condition, _order));
                if (_strTable.Contains("salEmployeeSalaryResult") || _strTable == "V_salBaseSalary" || _strTable.Contains("salSalaryInterception") || _strTable.Contains("salSalaryReissue") || _strTable == "V_salOvertimeFee" ||
                    _strTable == "V_salBasicSubsidy" || _strTable == "V_salLargeClassBonus" || _strTable == "V_salPerformanceBonus")
                {
                    EncryptData.EncryptSalary.DecryptLists(_strTable, dt);
                }
            }
            System.Data.DataSet ds = new DataSet();
            ds.Tables.Add(dt.Copy());
            rpt.DataSource = ds;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="rpt"></param>
        public void InitBands(XtraReport rpt)
        {
            DetailBand detail = new DetailBand();
            rpt.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { detail });
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="rep"></param>
        public void InitStyles(XtraReport rep)
        {
            XRControlStyle oddStyle = new XRControlStyle();
            XRControlStyle evenStyle = new XRControlStyle();

            oddStyle.BackColor = Color.LightBlue;
            oddStyle.StyleUsing.UseBackColor = true;
            oddStyle.StyleUsing.UseBorders = false;
            oddStyle.Name = "OddStyle";

            evenStyle.BackColor = Color.LightPink;
            evenStyle.StyleUsing.UseBackColor = true;
            evenStyle.StyleUsing.UseBorders = false;
            evenStyle.Name = "EvenStyle";

            rep.StyleSheet.AddRange(new DevExpress.XtraReports.UI.XRControlStyle[] { oddStyle, evenStyle });
        }

        public void InitDetailsBasedonXRTable(XtraReport rpt)
        {
            DataSet ds = ((DataSet)rpt.DataSource);

            DevExpress.XtraReports.UI.XRTable _tableDetail = rpt.FindControl("TDetail", true) as DevExpress.XtraReports.UI.XRTable;
            XRTable tableDetail = rpt.FindControl("table1", true) as DevExpress.XtraReports.UI.XRTable;

            XRTableRow detailRow = tableDetail.Rows[0];

            tableDetail.Rows.Add(detailRow);
            tableDetail.EvenStyleName = "EvenStyle";
            tableDetail.OddStyleName = "OddStyle";


            //{
            for (int i = 0; i < length; i++)
            {

                XRTableCell detailCell = detailRow.Cells[i];
                detailCell.WidthF = _colWidth[i];
                //detailCell.DataBindings.Add("Text", null, ds.Tables[0].Columns[i].Caption);
                detailCell.DataBindings.Add("Text", null, _field[i]);
                if (i == 0)
                {
                    //headerCell.Borders = DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top | DevExpress.XtraPrinting.BorderSide.Bottom;
                    detailCell.Borders = DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top | DevExpress.XtraPrinting.BorderSide.Bottom;
                }
                else
                {
                    //headerCell.Borders = DevExpress.XtraPrinting.BorderSide.All;
                    detailCell.Borders = DevExpress.XtraPrinting.BorderSide.All;
                }

                // Place the cells into the corresponding tables
                //headerRow.Cells.Add(headerCell);
                detailRow.Cells.Add(detailCell);
            }

            // Place the table onto a report's Detail band
            // rpt.Bands[BandKind.PageHeader].Controls.Add(tableHeader);
            rpt.Bands[BandKind.Detail].Controls.Add(tableDetail);
        }
    }
}